package com.cmcc.shared

import android.app.Activity
import java.util.*

/**
 * Author: jiangxin
 * Date: 2019/11/12
 * Description:
 */
class ActivityController {

    fun addActivity(activity: Activity) {
        activities.add(activity)
    }

    fun removeActivity(activity: Activity) {
        activities.remove(activity)
    }

    /**
     * 获取当前栈顶的activity
     *
     * @return
     */
    fun currentActivity(): Activity? {
        return if (activities.size > 0)
            activities[activities.size - 1]
        else
            null
    }

    fun finishAll() {
        for (activity in activities.drop(1)) {
            if (!activity.isFinishing) {
                activity.finish()
            }
        }
    }

    fun containClass(cls: Class<*>): Boolean {
        var tempActivity: Activity? = null
        for (act in activities) {
            if (act.javaClass == cls) {
                tempActivity = act
            }
        }
        return activities.contains(tempActivity)
    }

    fun finishSingleActivity(activity: Activity?) {
        activity?.finish()
    }

    fun finishSingleActivityByClass(cls: Class<*>) {
        var tempActivity: Activity? = null
        for (act in activities) {
            if (act.javaClass == cls) {
                tempActivity = act
            }
        }
        finishSingleActivity(tempActivity)
    }

    companion object {
        private val activities = LinkedList<Activity>()

        private var instance: ActivityController? = null

        private val `object` = Any()

        fun getInstance(): ActivityController {
            if (instance == null) {
                synchronized(`object`) {
                    if (instance == null) {
                        instance =
                            ActivityController()
                    }
                }
            }
            return instance!!
        }
    }
}